package com.example.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.api.entity.Course;
import com.example.api.entity.CourseOrder;
import com.example.api.entity.User;
import com.example.api.exception.CustomException;
import com.example.api.service.ICourseOrderService;
import com.example.api.service.ICourseService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

import static com.example.api.dto.ResStatusCode.COURSE_ORDER_ERROR;
import static com.example.api.dto.ResStatusCode.COURSE_QUERY_ERROR;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author TeacherLi
 * @since 2020-09-06
 */
@RestController
@RequestMapping("/api/course-order")
public class CourseOrderController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CourseOrderController.class);

    @Autowired
    private ICourseService courseService;
    @Autowired
    private ICourseOrderService orderService;

    @PostMapping("/{courseId}")
    @ApiOperation("课程购买接口")
    @PreAuthorize("hasAuthority('ROLE_USER')")
    public ResponseEntity<CourseOrder> buyCourse(
            @ApiParam("课程ID")
           @PathVariable(value = "courseId",required = true)
            Long courseId
    ){

        User user = getUser();
        if(user==null){

            return ResponseEntity.badRequest().build();

        }

        try {
            Course course =  courseService.getById(courseId);
            if(course!=null){

                CourseOrder order = new CourseOrder();
                order.setCourseId(courseId);
                order.setUserId(user.getId());
                //先查询是否已有订单
                QueryWrapper<CourseOrder> queryWrapper = new QueryWrapper<>();

                queryWrapper.setEntity(order);

                List<CourseOrder> orders = orderService.list(queryWrapper);
                if(!orders.isEmpty()){
                    return ResponseEntity.ok(orders.get(0));
                }

                //下单 实际情况 引导用户支付
                order.setCourseTitle(course.getTitle());
                order.setCreateTime(LocalDateTime.now());
                order.setOrderStatus(2);
                order.setOrderTime(LocalDateTime.now());
                order.setPayPrice(course.getPrice());
                order.setPayTime(LocalDateTime.now());

                orderService.save(order);

                //更新课程购买人数
                courseService.updateSaleCount(courseId);

                return ResponseEntity.ok(order);

            }else {
                throw new CustomException(courseId+"",COURSE_QUERY_ERROR.getCode(),COURSE_QUERY_ERROR.getMessage());
            }
        } catch (CustomException e) {
            log.error(e.getMessage(),e);
            throw  new CustomException(courseId+"",COURSE_ORDER_ERROR.getCode(),COURSE_ORDER_ERROR.getMessage());
        }
    }



}
